const db = require('../db/index')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const Secret = require('../config')
// 注册
exports.regUser = (req, res) => {
  const userinfo = req.body
  if (!userinfo.username || !userinfo.password) {
    return res.cc('用户名或密码不为空!')
  }
  const sql = 'select * from ev_users2 where username = ?'
  db.query(sql, userinfo.username, (err, result) => {
    if (err) return res.cc(err)
    if (result.length !== 0) return res.cc('用户名已被占用!')
    userinfo.password = bcrypt.hashSync(userinfo.password, 10)
    const sql = 'insert into ev_users2 set ?'
    db.query(sql, {username:userinfo.username, password:userinfo.password}, (err, result) => {
      if (err) return res.cc(err)
      if (result.affectedRows !== 1) return res.cc('注册失败,请稍后再试')
      res.cc('注册用户成功', 0)
    })
  })
}
//登录
exports.login = (req, res) => {
  const userinfo = req.body
  if (!userinfo.username || !userinfo.password) {
    return res.cc('用户名或密码不为空!')
  }
  const sql = 'select * from ev_users2 where username = ?'
  db.query(sql, userinfo.username, (err, result)=>{
    if(err) return res.cc(err)
    if(result.length !== 1) return res.cc('用户不存在!')
    const compareResult = bcrypt.compareSync(userinfo.password, result[0].password)
    if(!compareResult) return res.cc('密码输入错误')
    const users = {...result[0], password: '', user_pic: ''}
    const token = jwt.sign(users, Secret.jwtSecretKey, {expiresIn: '30h'})
    res.send({
      status: 0,
      message: '登陆成功',
      token: 'Bearer ' + token
    })
  })
}